<!--
 * @页面名称:全局表格
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <vxe-grid
    ref="gridTable"
    :border="border"
    :size="size === 'default' ? 'small' : size === 'small' ? 'mini' : size === 'large' ? 'medium' : ''"
    :row-config="{ isCurrent: true, isHover: true }"
    show-header-overflow
    show-overflow
    :height="height"
    :scrollY="{ enabled: true, gt: 0 }"
    :loading="loading"
    :loadingConfig="{ text: loadingText }"
    :data="data"
    :columns="columns"
    :checkbox-config="{ highlight: true, range: true, checkField: 'checkbox' }"
    :column-config="{ resizable: true, useKey: true }"
    :toolbar-config="toolbarConfig"
    :print-config="{}"
    :import-config="{}"
    :export-config="{}"
    :seq-config="{ startIndex: (tablePage.pageIndex - 1) * tablePage.pageSize }"
    :menu-config="tableMenu"
    @menu-click="rightMenuClick"
    @cell-click="cellClick"
    @cell-dblclick="cellDblclick"
    @checkbox-change="checkboxChange"
    @checkbox-all="checkboxAll"
    @checkbox-range-end="checkboxRangeEnd"
  >
    <template #toolbarButtons>
      <slot name="toolbarButtons"></slot>
    </template>
    <template #Status_default="{ row }">
      <span v-if="showStatus" :class="['circle', dynamicClass[row.Status]['class']]">{{ dynamicClass[row.Status]["name"] }}</span>
    </template>
    <!-- 分页 -->
    <template #pager>
      <vxe-pager
        v-if="tablePage.showPage"
        :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
        v-model:current-page="tablePage.pageIndex"
        v-model:page-size="tablePage.pageSize"
        :page-sizes="pageSizes"
        :total="tablePage.total"
        @page-change="handlePageChange"
      >
      </vxe-pager>
    </template>
  </vxe-grid>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { useGlobalStore } from "@/stores/modules/global";
import { VxeTableInstance, VxeGridProps, VxeTablePropTypes, VxeColumnPropTypes, VxeUI } from "vxe-table";
import Sortable from "sortablejs";

const props = defineProps({
  height: {
    type: String || Number,
    default: () => {
      return "auto";
    }
  },
  border: {
    type: Boolean,
    default: () => {
      return true;
    }
  },
  loading: {
    type: Boolean,
    default: () => {
      return false;
    }
  },
  loadingText: {
    type: String,
    default: () => {
      return "正在加载中...";
    }
  },
  tablePage: {
    type: Object,
    default: () => {
      return {
        showPage: false,
        pageIndex: 1,
        pageSize: 10,
        total: 0
      };
    }
  },
  pageSizes: {
    type: Array as any,
    default: () => {
      return undefined;
    }
  },
  columns: {
    type: Array as any,
    default: () => {
      return [];
    }
  },
  data: {
    type: Array,
    default: () => {
      return [];
    }
  },
  rowId: {
    type: String,
    default: "_X_ROW_KEY"
  },
  tableMenu: {
    type: Object,
    default: () => {
      return {
        // enabled: true,
        // className: 'my-menus',
        // body: {
        //   options: [
        //     [
        //       { code: 'copy', name: '测试按钮', prefixIcon: 'fa fa-copy', className: 'my-copy-item' }
        //     ]
        //   ]
        // }
      };
    }
  },
  showStatus: {
    type: Boolean,
    default: false
  },
  toolbarConfigVisible: {
    type: Boolean,
    default: false
  },
  proxyConfig: {
    type: Object,
    default: () => {
      return {
        autoLoad: false,
        response: {
          result: "result",
          total: "page.total"
        },
        ajax: {
          // 接收 Promise
          query: () => {
            return null;
          }
        }
      };
    }
  }
});
const dynamicClass = reactive<any>({
  0: { class: "circle-bg0", name: "删除" },
  1: { class: "circle-bg1", name: "预归" },
  11: { class: "circle-bg11", name: "待审" },
  12: { class: "circle-bg12", name: "退回" },
  2: { class: "circle-bg2", name: "整理" },
  21: { class: "circle-bg21", name: "待存" },
  22: { class: "circle-bg22", name: "退整" },
  3: { class: "circle-bg3", name: "保存" }
});
// 工具栏配置
const toolbarConfig = reactive({
  refresh: {
    icon: "vxe-icon-refresh",
    iconLoading: "vxe-icon-refresh roll",
    queryMethod: () => emit("refresh")
  },
  import: {
    icon: "vxe-icon-cloud-upload"
  },
  export: {
    icon: "vxe-icon-cloud-download"
  },
  print: {
    icon: "vxe-icon-print"
  },
  zoom: {
    iconIn: "vxe-icon-fullscreen",
    iconOut: "vxe-icon-minimize"
  },
  custom: {
    icon: "vxe-icon-menu"
  },
  slots: {
    buttons: "toolbarButtons"
  },
  enabled: props.toolbarConfigVisible
});
const emit = defineEmits(["rowClick", "rowdblClick", "selectionChange", "pageChange", "menuClick", "refresh"]);
const globalStore = useGlobalStore();
// 系统色
const isDark = computed(() => (globalStore.isDark ? true : false));
if (isDark.value) {
  VxeUI.setTheme("dark");
} else {
  VxeUI.setTheme("light");
}
// 全局组件尺寸
const size = computed<any>(() => globalStore.assemblySize);
// 计时器标识
const timer = ref();
// 表格实例
const gridTable = ref<VxeTableInstance>();
// 单击事件
const cellClick = ({ row, rowIndex, column }: any) => {
  clearTimeout(timer.value);
  timer.value = setTimeout(() => {
    // 筛除多选时单击触发操作
    if (!column.field) {
      return;
    }
    emit("rowClick", { row, rowIndex });
  }, 30);
};
// 双击事件
const cellDblclick = ({ row, rowIndex, column }: any) => {
  clearTimeout(timer.value);
  // 筛除多选时单击触发操作
  if (!column.field) {
    return;
  }
  emit("rowdblClick", { row, rowIndex });
};
// 勾选
const checkboxChange = ({ checked }: any) => {
  emit("selectionChange", getCheckboxRecords());
};
// 全部勾选
const checkboxAll = ({ checked }: any) => {
  emit("selectionChange", getCheckboxRecords());
};
// 快捷勾选
const checkboxRangeEnd = ({ checked }: any) => {
  emit("selectionChange", getCheckboxRecords());
};
// 清除全部全选操作
const clearCheckboxRow = () => {
  gridTable.value.clearCurrentRow();
  gridTable.value.clearCheckboxRow();
};
// 多选操作勾选某行
const setCheckboxRow = (rows: any, checked: boolean) => {
  if (rows.length === 0) {
    // 清除全部多选选择
    clearCheckboxRow();
  } else {
    clearCheckboxRow();
    gridTable.value.setCheckboxRow(rows, checked);
  }
};
// 右键事件
const rightMenuClick = ({ menu, row, column }: any) => {
  console.log("右键菜单触发", menu);
  emit("menuClick", { menu, row, column });
};
// 获取所有勾选项
const getCheckboxRecords = () => {
  return gridTable.value.getCheckboxRecords();
};
// 分页事件
const handlePageChange = ({ currentPage, pageSize }: any) => {
  props.tablePage.pageIndex = currentPage;
  props.tablePage.pageSize = pageSize;
  emit("pageChange", { pageIndex: currentPage, pageSize });
};
// 局部加载页面数据
const reloadData = (data: any) => {
  gridTable.value.loadData(data || []);
};
// 行拖动
let sortable1: any;

const rowDrop = (data: any[]) => {
  const $table = gridTable.value;
  sortable1 = Sortable.create($table.$el.querySelector(".body--wrapper>.vxe-table--body tbody"), {
    handle: ".vxe-body--column",
    onEnd: sortableEvent => {
      const newIndex = sortableEvent.newIndex as number;
      const oldIndex = sortableEvent.oldIndex as number;
      const currRow = data.splice(oldIndex, 1)[0];
      data.splice(newIndex, 0, currRow);
      console.log(data);
    }
  });
};
// 排序
const sortEvent = (field: VxeColumnPropTypes.Field, order: VxeTablePropTypes.SortOrder) => {
  const $grid = gridTable.value;
  if ($grid) {
    $grid.sort({ field, order });
  }
};
defineExpose({
  reloadData,
  setCheckboxRow,
  rowDrop,
  gridTable,
  sortEvent
});
</script>

<style lang="scss">
@import "@/styles/vxe-table.scss";

// @import "./index.scss";
// .vxe-grid {
//   height: 100%;
//   :deep(.row--checked) {
//     background-color: var(--el-color-primary-light-6) !important;
//   }
// }
.circle {
  display: inline-block;
  width: 28px;
  height: 18px;
  font-size: 12px;
  line-height: 18px;
  text-align: center;
  border-radius: 2px;
}
.circle-bg1,
.circle-bg11,
.circle-bg2,
.circle-bg21,
.circle-bg3 {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-6);
  box-shadow: 0 0 3px var(--el-color-primary);
}
.circle-bg12,
.circle-bg22 {
  color: #ffffff;
  background: red;
  box-shadow: 0 0 3px var(--el-color-primary);
}
</style>
